#include "global.hpp"
#include "CommandHandler.hpp"
using boost::asio::ip::tcp;

class Session : public std::enable_shared_from_this<Session>
{
public:
    Session(tcp::socket socket);
    void Start();
    ~Session();

    // 为CommandHandler提供访问接口
    void SendResponse(int code, const std::string &msg);
    std::string GetCurrentDirectory() const { return current_dir_; }
    void SetCurrentDirectory(const std::string &dir) { current_dir_ = dir; }
    bool IsLoggedIn() const { return logged_in_; }
    void SetLoggedIn(bool status) { logged_in_ = status; }
    std::string GetUsername() const { return username_; }
    void SetUsername(const std::string &user) { username_ = user; }

    // 数据连接相关
    enum DataMode
    {
        ACTIVE,
        PASSIVE
    };
    DataMode GetDataMode() const { return data_mode_; }
    void SetDataMode(DataMode mode) { data_mode_ = mode; }
    tcp::socket &GetDataSocket() { return data_socket_; }
    tcp::endpoint GetPassiveEndpoint() const { return passive_endpoint_; }
    void SetPassiveEndpoint(const tcp::endpoint &endpoint) { passive_endpoint_ = endpoint; }

private:
    void ReadCommand();
    void HandleCommand(const std::string &command);
    bool IsSocketOpen() const;
    tcp::endpoint GetRemoteEndpoint() const;

    tcp::socket control_socket_;
    std::shared_ptr<spdlog::logger> logger_;
    std::shared_ptr<CommandHandler> command_handler_;
    boost::asio::streambuf input_buffer_;

    // 会话状态
    std::string username_;
    std::string current_dir_;
    bool logged_in_ = false;
    DataMode data_mode_ = PASSIVE; // 默认被动模式

    // 数据连接相关
    tcp::socket data_socket_;        // 用于主动模式
    tcp::endpoint passive_endpoint_; // 被动模式下的监听端点

    std::atomic<bool> socket_closed_{false};
};
